package com.wang.mall.config.feign;

import com.google.common.net.HttpHeaders;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 使用 用户的 token进行 远程调用的身份认证
 * 远程调用的身份认证
 */
@Slf4j
public class Auth2FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 1 我们可以从request的上下文的环境中获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            // 请求为空
            log.info("没有请求的上下文,无法进行token传递");
        }

        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取请求上下文 里面的AUTHORIZATION
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (!StringUtils.isEmpty(header)) {
            requestTemplate.header(HttpHeaders.AUTHORIZATION, header);
            log.info("本次token传递成功,值为={}", header);
        }
    }
}
